//
//  AppDelegate.m
//  AILock
//
//  Created by 谭亚明 on 2020/6/17.
//  Copyright © 2020 tym. All rights reserved.
//
#import "ESPTools.h"
#import "ShowAlertView.h"
#import "AppDelegate.h"
#import "ViesionDataView.h"
#import "UserService.h"
#import "YYModel.h"
#import <Bugly/Bugly.h>
#import "TYMNavigationController.h"
#import "MessageHistoryVC.h"
#import "IQKeyboardManager.h"
#import "NSString+Option.h"
#import "ESP_NetUtil.h"
#import "MainViewController.h"
// 引入 JPush 功能所需头文件
#import "JPUSHService.h"
// iOS10 注册 APNs 所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// 如果需要使用 idfa 功能所需要引入的头文件（可选）
#import <AdSupport/AdSupport.h>

@interface AppDelegate ()<JPUSHRegisterDelegate>

@property(nonatomic,strong) UserService *services;
@property(nonatomic,strong) VersionModel *versionModel;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.window.frame=CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width,  [UIScreen mainScreen].bounds.size.height);
    
    MainViewController  *vc=[[MainViewController alloc]init];
    self.window.rootViewController = vc;
    [self.window makeKeyAndVisible];
    
    [ESP_NetUtil tryOpenNetworkPermission];
    
    
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    if (@available(iOS 12.0, *)) {
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound|JPAuthorizationOptionProvidesAppNotificationSettings;
    } else {
        // Fallback on earlier versions
    }

    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    [JPUSHService setupWithOption:launchOptions appKey:@"668c3072f2fcd9c9a42566f6"
                          channel:@"app store"
                 apsForProduction:NO
            advertisingIdentifier:nil];
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功：%@",registrationID);
            
        }
        else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    
    [self  getVersionModel];
    
    [Bugly startWithAppId:@"f544d111d0"];
    
    [WXApi startLogByLevel:WXLogLevelDetail logBlock:^(NSString *log) {
        NSLog(@"WeChatSDK: %@", log);
    }];
    [WXApi registerApp:@"wx66eb63cc7ec87ebe"
    universalLink:@"https://www.xsun-lock.com/"];
    return YES;
}

//微信回调
-(void)onResp:(BaseResp *)resp
{
     if ([resp isKindOfClass:[WXLaunchMiniProgramResp class]])
     {
          //NSString *string = resp.extMsg;
          // 对应JsApi navigateBackApplication中的extraData字段数据
     }
}

-(UserService*)services{
    if (_services == nil) {
        _services = [[UserService alloc] init];
    }
    return _services;
}

-(void)getVersionModel{
    TYMWeak(self);
    [self.services getFindnewversion:^(LMJBaseResponse * _Nonnull respon, VersionModel * _Nonnull version) {
        weakself.versionModel = version;
        [weakself updateVersion];
    }];
}

-(void)updateVersion{
    if ([self compareVesionWithServerVersion:self.versionModel.versionNo]) {
        
        ViesionDataView  *pop = [[ViesionDataView alloc]initWithFrame:self.window.bounds];
        pop.blockCallBackIndex = ^{
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://apps.apple.com/cn/app/%E5%BE%AE%E4%BF%A1/id1421601183"] options:@{} completionHandler:^(BOOL success) {
                }];
            } else {
            }
        };
        pop.data = self.versionModel;
        [pop viewShow];
    }
}

//收到极光自定义消息
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary * userInfo = [notification userInfo];
    NSString *content = [userInfo valueForKey:@"content"];
    //挤掉登录
    if ([content isEqualToString:@"signout.auto"]) {
        [UserTool clearUserInfocompletion:nil];
        [ShowAlertView showAlertViewTitle:@"提示" message:@"您的账号已在另一台设备登录" actionBtnTitle:@"确定"
                             hiddenCancel:YES
                               completion:^(NSInteger actionType) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"showLoginView" object:nil];
        }];
    }else{
        NSDictionary *dic = [NSString dictionaryWithJsonString:content];
        switch ([dic[@"code"] integerValue]) {
            case 30: // 添加指纹锁用户
                [[NSNotificationCenter defaultCenter] postNotificationName:@"addPasswordCurrAction" object:dic[@"data"]];
                break;
            case 100:
                [[NSNotificationCenter defaultCenter] postNotificationName:@"addEquipmentSuccess" object:dic[@"data"]];
                NSLog(@"++++++++++++++++++++--------------------/");
                break;
            case 110: // 授予家长权限推送
                
                
                break;
            case 111:     // 家庭用户审核推送
                
                break;
            case 31:  // 本地用户新增
                
                break;
            case 36:  // 本地用户修改
                
                break;
            case 32: // 本地用户删除
                break;
            case 39:  //锁配置上报updateEquipmentConfigInfo
                [[NSNotificationCenter defaultCenter] postNotificationName:@"updateEquipmentConfigInfo" object:nil];
                break;
            default:
                break;
        }
    }
}

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

-(void)applicationDidBecomeActive:(UIApplication *)application{
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [JPUSHService setBadge:0];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return  [WXApi handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [WXApi handleOpenURL:url delegate:self];
}

-(BOOL)application:(UIApplication*)application continueUserActivity:(nonnull NSUserActivity *)userActivity restorationHandler:(nonnull void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler{
    return  [WXApi handleOpenUniversalLink:userActivity delegate:self];
}

#pragma mark- JPUSHRegisterDelegate

// iOS 12 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification{
    if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //从通知界面直接进入应用
    }else{
        //从通知设置界面进入应用
    }
}


//收到通知
// iOS 10 Support应用处于前台的状态下收到推送消息会调用此方法
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    NSDictionary * userInfo = notification.request.content.userInfo;
    if (@available(iOS 10.0, *)) {
        if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            [JPUSHService handleRemoteNotification:userInfo];
        }
    } else {
        
    }
    NSDictionary *dataDic = [NSString dictionaryWithJsonString:userInfo[@"Json"]];
    switch ([dataDic[@"code"] intValue]) {
        case 28: //开关门上报
            
            break;
        case 29: //事件报警
            // [[NSNotificationCenter defaultCenter] postNotificationName:@"updateLockState" object:dataDic];
            break;
        case 50: //本地开关门申请
            [[NSNotificationCenter defaultCenter] postNotificationName:@"homeEqumentupdateLockState" object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"updateLockState" object:dataDic];
            break;
        case 52: //设备上线通知
            
            
            break;
            
            //        case 100: //设备绑定推送
            //
            //            break;
            //        case 110: //授予家长权限推送
            //
            //            break;
            //        case 111://家庭用户审核推送
            //
            //            break;
            //        case 112://申请成为家庭用户推送
            //
            //            break;
            //        case 31: //本地用户新增
            //
            //            break;
            //        case 36: //本地用户修改
            //
            //            break;
            //        case 32://本地用户删除
            //
            //            break;
        case 38: //本地初始化
            
            break;
        default:
            break;
    }
    if (@available(iOS 10.0, *)) {
        completionHandler(UNNotificationPresentationOptionAlert);
    } else {
        // Fallback on earlier versions
    } // 需要执行这个方法，选择是否提醒用户，有 Badge、Sound、Alert 三种类型可以选择设置
}

// iOS 10 Support当收到推送通知后打开推送消息会调用此方法
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if (@available(iOS 10.0, *)) {
        if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            [JPUSHService handleRemoteNotification:userInfo];
        }
    } else {
        // Fallback on earlier versions
    }
    
    [self didJpushJumpToDetail:userInfo];
    completionHandler();  // 系统要求执行这个方法
}

//iOS7及以上系统，收到通知      此方法在接收到静默推送的时候会调用
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    if (application.applicationState != UIApplicationStateActive) {//不在前台，必须判断
        [self didJpushJumpToDetail:userInfo];
    }
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

#pragma mark - getter
- (UIWindow *)window
{
    if(!_window)
    {
        _window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        [_window makeKeyAndVisible];
    }
    return _window;
}

//实现点击通知跳转到相应的详情界面
- (void)didJpushJumpToDetail:(NSDictionary *)userInfo {
    [self performSelector:@selector(didJPumpToDetail:) withObject:userInfo afterDelay:0.1];
}

-(void)didJPumpToDetail:(id)sender{
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"didJPumpToDetail" object:sender];
}

/**
 比较两个版本号的大小
 @param version APP Store 版本号
 @return 版本号相等,返回NO;大于 返回YES
 */
- (BOOL)compareVesionWithServerVersion:(NSString *)version {
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    if ([version compare:[infoDictionary objectForKey:@"CFBundleShortVersionString"] options:NSNumericSearch] == NSOrderedDescending) {
        return YES;
    }else{
        return NO;
    }
}

@end
